package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cyzy.dto.OrderCreateDto;
import com.cyzy.dto.Result;
import com.cyzy.mapper.OredrsMapper;
import com.cyzy.mapper.UserMapper;
import com.cyzy.pojo.Orders;
import com.cyzy.pojo.User;
import com.cyzy.service.ScoreOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Slf4j
@Service
public class ScoreOrderServiceImpl implements ScoreOrderService {
    
    @Autowired
    private OredrsMapper ordersMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result createScoreOrder(OrderCreateDto orderCreateDto) {
        try {
            // 1. 检查用户是否存在
            User user = userMapper.selectById(orderCreateDto.getUser_id());
            if (user == null) {
                return Result.error().message("用户不存在");
            }
            
            // 2. 检查用户积分是否足够
            Integer userScore = user.getUserScore();
            if (userScore == null) {
                userScore = 0;
            }
            
            Double orderAmount = orderCreateDto.getOrder_amount();
            if (orderAmount == null || orderAmount <= 0) {
                return Result.error().message("订单金额不能为空或小于等于0");
            }
            
            if (userScore < orderAmount.intValue()) {
                return Result.error().message("积分不足，当前积分：" + userScore + "，需要积分：" + orderAmount.intValue());
            }
            
            // 3. 创建订单记录
            Orders order = new Orders();
            order.setOrderNum(orderCreateDto.getOrder_num());
            order.setUserId(orderCreateDto.getUser_id().longValue());
            order.setOrderType(orderCreateDto.getOrder_type());
            order.setRelatedId(orderCreateDto.getRelated_id() != null ? orderCreateDto.getRelated_id().longValue() : 0L);
            order.setOrderAmount(orderCreateDto.getOrder_amount());
            order.setOrderStatus(1L); // 已付款
            order.setPayTime(Timestamp.valueOf(LocalDateTime.now())); // 当前时间
            order.setLeastTime(orderCreateDto.getLeast_time() != null ? orderCreateDto.getLeast_time() : 0);
            order.setOrderAddressId(orderCreateDto.getOrder_address_id() != null ? orderCreateDto.getOrder_address_id().longValue() : 0L);
            order.setOrderQuantity(orderCreateDto.getOrder_quantity() != null ? orderCreateDto.getOrder_quantity() : 1);
            
            // 插入订单
            int insertResult = ordersMapper.insert(order);
            if (insertResult <= 0) {
                return Result.error().message("订单创建失败");
            }
            
            // 4. 扣除用户积分
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getUserId, orderCreateDto.getUser_id().longValue())
                    .set(User::getUserScore, userScore - orderAmount.intValue());
            
            int updateResult = userMapper.update(null, updateWrapper);
            if (updateResult <= 0) {
                return Result.error().message("积分扣除失败");
            }
            
            log.info("积分订单创建成功，订单号：{}，用户ID：{}，扣除积分：{}", 
                    orderCreateDto.getOrder_num(), orderCreateDto.getUser_id(), orderAmount.intValue());
            
            return Result.ok()
                    .data("orderId", order.getOrderId())
                    .data("orderNum", order.getOrderNum())
                    .data("remainingScore", userScore - orderAmount.intValue())
                    .message("积分订单创建成功");
                    
        } catch (Exception e) {
            log.error("创建积分订单时发生异常：", e);
            return Result.error().message("创建订单时发生异常：" + e.getMessage());
        }
    }
}